<template>
  <Dialog
    v-model="dialogVisible"
    class="user-select-form-dialog"
    top="50px"
    title="人员选择"
    width="800px"
  >
    <el-tabs v-model="activeTab" class="user-select-form-tabs" @tab-change="handleTabChange">
      <!-- 部门选择标签页 -->
      <el-tab-pane label="按部门选择" name="dept">
        <div class="user-select-form-content">
          <UserSelectPanel
            ref="deptPanelRef"
            :tree-data="deptTree"
            :tree-props="defaultProps"
            :user-list="userList"
            :filtered-user-list="filteredUserList"
            v-model="selectedUserIdList"
            :form-loading="formLoading"
            @node-click="handleNodeClick"
          />
        </div>
      </el-tab-pane>
      <!-- 岗位选择标签页 -->
      <el-tab-pane label="按岗位选择" name="post">
        <div class="user-select-form-content">
          <UserSelectPanel
            ref="postPanelRef"
            :tree-data="postTree"
            :tree-props="defaultProps"
            :user-list="userList"
            :filtered-user-list="filteredPostList"
            v-model="selectedUserIdList"
            :form-loading="formLoading"
            @node-click="handlePostNodeClick"
          />
        </div>
      </el-tab-pane>
      <!-- 群组选择标签页 -->
      <el-tab-pane label="按群组选择" name="group">
        <div class="user-select-form-content">
          <UserSelectPanel
            ref="groupPanelRef"
            :tree-data="groupTree"
            :tree-props="groupDefaultProps"
            :user-list="userList"
            :filtered-user-list="filteredGroupUserList"
            v-model="selectedUserIdList"
            :form-loading="formLoading"
            @node-click="handleGroupNodeClick"
          />
        </div>
      </el-tab-pane>
    </el-tabs>

    <template #footer>
      <el-button
        :disabled="formLoading || !selectedUserIdList?.length"
        type="primary"
        @click="submitForm"
      >
        确 定
      </el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
import { defaultProps, handleTree } from '@/utils/tree'
import * as DeptApi from '@/api/system/dept'
import * as UserApi from '@/api/system/user'
import * as PostApi from '@/api/system/post'
import * as UserGroupApi from '@/api/bpm/userGroup'
import UserSelectPanel from './UserSelectPanel.vue'
const props = defineProps({
  // 初始是否请求数据
  isInitGet: {
    type: Boolean,
    default: false
  },
  // 确认是否提示成功信息
  notSuccessMessage: {
    type: Boolean,
    default: false
  }
})
defineOptions({ name: 'UserSelectForm' })
const emit = defineEmits<{
  confirm: [id: any, userList: any[]]
}>()
const { t } = useI18n() // 国际
const message = useMessage() // 消息弹窗
const deptTree = ref<Tree[]>([]) // 部门树形结构化
const deptList = ref<any[]>([]) // 保存扁平化的部门列表数据
const userList = ref<UserApi.UserVO[]>([]) // 所有用户列表
const filteredUserList = ref<UserApi.UserVO[]>([]) // 当前部门过滤后的用户列表
// 岗位相关数据
const postTree = ref<PostApi.PostVO[]>([]) // 岗位列表
const filteredPostList = ref<UserApi.UserVO[]>([]) // 当前岗位过滤后的用户列表
// 群组相关数据
const groupTree = ref<UserGroupApi.UserGroupVO[]>([]) // 群组列表
const filteredGroupUserList = ref<UserApi.UserVO[]>([]) // 当前群组过滤后的用户列表
// 引用
const deptPanelRef = ref()
const postPanelRef = ref()
const groupPanelRef = ref()
const selectedUserIdList: any = ref([]) // 选中的用户列表
const dialogVisible = ref(false) // 弹窗的是否展示
const formLoading = ref(false) // 表单的加载中
const activityId = ref()
const activeTab = ref('dept') // 当前激活的标签页
const groupDefaultProps = { children: 'children', label: 'name', value: 'id' } // 群组树的默认配置

const getData = async (selectedList?: any[]) => {
  if (!userList.value?.length) {
    // 如果用户列表为空，则重新加载
    // 加载部门、用户列表
    const deptData = await DeptApi.getSimpleDeptList()
    deptList.value = deptData // 保存扁平结构的部门数据
    deptTree.value = handleTree(deptData) // 转换成树形结构
    userList.value = await UserApi.getSimpleUserList()
  }
  // 加载岗位列表
  if (!postTree.value?.length) {
    const postData = await PostApi.getSimplePostList()
    postTree.value = postData
  }
  // 加载群组列表
  if (!groupTree.value?.length) {
    const groupData = await UserGroupApi.getUserGroupSimpleList()
    // 将群组数据转换为树形结构（虽然目前可能只有一级）
    groupTree.value = groupData.map((group) => ({
      ...group,
      children: []
    }))
  }
  nextTick(() => {
    handleTabChange(activeTab.value)
  })
  selectedUserIdList.value = selectedList?.map((item: any) => item.id) || []
}
/** 打开弹窗 */
const open = async (id: number, selectedList?: any[]) => {
  activityId.value = id
  resetForm()
  await getData(selectedList)
  dialogVisible.value = true
}

/** 获取指定部门及其所有子部门的ID列表 */
const getChildDeptIds = (deptId: number, deptList: any[]): number[] => {
  const ids = [deptId]
  const children = deptList.filter((dept) => dept.parentId === deptId)
  children.forEach((child) => {
    ids.push(...getChildDeptIds(child.id, deptList))
  })
  return ids
}

/** 获取部门过滤后的用户列表 */
const filterUserList = async (deptId?: number) => {
  formLoading.value = true
  try {
    if (!deptId) {
      // 如果没有选择部门，显示所有用户
      filteredUserList.value = [...userList.value]
      return
    }

    // 直接使用已保存的部门列表数据进行过滤
    const deptIds = getChildDeptIds(deptId, deptList.value)

    // 过滤出这些部门下的用户
    filteredUserList.value = userList.value.filter((user) => deptIds.includes(user.deptId))
  } finally {
    formLoading.value = false
  }
}
const groupData = ref({})
/** 获取群组过滤后的用户列表 */
const filterGroupUserList = async (groupId?: number) => {
  formLoading.value = true
  try {
    if (!groupId) {
      // 如果没有选择群组，显示所有用户
      filteredGroupUserList.value = [...userList.value]
      return
    }
    let group = groupData.value[groupId]
    if (!group) {
      // 查找选中的群组
      group = await UserGroupApi.getUserGroup(groupId)
      if (!group || !group.userIds || !group.userIds.length) {
        filteredGroupUserList.value = []
        return
      }
      groupData.value[groupId] = group
    }
    const userIds = group.userIds
    // 过滤出这些群组下的用户
    filteredGroupUserList.value = userList.value.filter((user) => userIds.includes(user.id))
  } finally {
    formLoading.value = false
  }
}
const postData = ref({})
/** 获取岗位过滤后的用户列表 */
const filterPostUserList = async (postId?: number) => {
  formLoading.value = true
  try {
    if (!postId) {
      // 如果没有选择岗位，显示所有用户
      filteredPostList.value = [...userList.value]
      return
    }
    let userIds = postData.value[postId]
    if (!userIds) {
      // 查找选中的岗位
      const data = await UserApi.getUsersByPostId([postId])
      if (!data || !data.length) {
        filteredPostList.value = []
        return
      }
      userIds = postData.value[postId] = data.map((item: any) => item.id)
    }
    // 过滤出这些岗位下的用户
    filteredPostList.value = userList.value.filter((user) => userIds.includes(user.id))
  } finally {
    formLoading.value = false
  }
}

/** 提交选择 */
const submitForm = async () => {
  try {
    if (!props.notSuccessMessage) message.success(t('common.updateSuccess'))
    dialogVisible.value = false
    // 从所有用户列表中筛选出已选择的用户
    const emitUserList = userList.value.filter((user: any) =>
      selectedUserIdList.value.includes(user.id)
    )
    // 发送操作成功的事件
    emit('confirm', activityId.value, emitUserList)
  } finally {
  }
}

/** 重置表单 */
const resetForm = () => {
  if (!userList.value?.length) {
    // 如果用户列表为空，则重置列表
    deptTree.value = []
    deptList.value = []
    userList.value = []
  }
  filteredUserList.value = []
  selectedUserIdList.value = []
}

/** 处理部门被点击 */
const handleNodeClick = (row: { [key: string]: any }) => {
  filterUserList(row.id)
}
/** 处理岗位被点击 */
const handlePostNodeClick = (row: { [key: string]: any }) => {
  filterPostUserList(row.id)
}
/** 处理群组被点击 */
const handleGroupNodeClick = (row: { [key: string]: any }) => {
  filterGroupUserList(row.id)
}

/** 处理标签页切换 */
const handleTabChange = (tab: any) => {
  // 切换标签页时，重置过滤列表
  if (tab === 'dept') {
    filteredUserList.value = [...userList.value]
    filteredGroupUserList.value = []
    const deptTreeItem = deptTree.value[0]
    deptPanelRef.value?.treeRef?.setCurrentKey(deptTreeItem?.id)
    // filterUserList(deptTreeItem?.id)
  } else if (tab === 'group') {
    filteredGroupUserList.value = []
    filteredUserList.value = []
    const groupTreeItem = groupTree.value[0]
    groupPanelRef.value?.treeRef?.setCurrentKey(groupTreeItem?.id)
    filterGroupUserList(groupTreeItem?.id)
  } else if (tab === 'post') {
    filteredPostList.value = []
    filteredUserList.value = []
    const postTreeItem = postTree.value[0]
    postPanelRef.value?.treeRef?.setCurrentKey(postTreeItem?.id)
    filterPostUserList(postTreeItem?.id)
  }
}
if (props.isInitGet) {
  getData()
}
defineExpose({ open, userList, deptPanelRef, groupPanelRef }) // 提供 open 方法，用于打开弹窗
</script>
<style lang="scss">
.user-select-form-dialog {
  .el-dialog__body {
    padding-top: 0 !important;
    overflow: hidden;
  }
}
</style>
<style lang="scss" scoped>
.user-select-form-tabs {
  position: sticky;
  top: 0;
  z-index: 10;
}

.user-select-form-content {
  max-height: 600px;
  min-height: 600px;
  padding: 10px;
  overflow-y: hidden;
}
</style>
